import * as React from "react";


interface InputProps {
  value?: string;
  defaultValue?: string;
  onChange?: (value: string) => void;
}

export default class Input extends React.Component<InputProps, any> {

  constructor(props: InputProps) {
    super(props);
    const {value, defaultValue} = props;
    this.state = {
      value: 'value' in props ? value : ('defaultValue' in props ? defaultValue : '')
    }
  }

  static getDerivedStateFromProps(nextProps:any, prevState:any) {
    if ('value' in nextProps && nextProps.value !== prevState.value) {
      return {value: nextProps.value}
    }
    return null;
  }

  // componentDidUpdate(prevProps: Readonly<InputProps>, prevState: Readonly<any>, snapshot?: any) {
  //   if ('value' in prevProps && prevProps.value !== this.state.value) {
  //     this.setState({value: prevProps.value})
  //   }
  // }

  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.currentTarget.value;
    if ('value' in this.props) {
      const {onChange} = this.props;
      if (onChange) {
        onChange(value);
      }
    } else {
      this.setState({value});
      const {onChange} = this.props;
      if (onChange) {
        onChange(value);
      }
    }
  }


  render() {
    const {value} = this.state;
    return (
      <input type="text" value={value} onChange={this.handleChange} />
    )
  }

}

